#!/usr/bin/env python
# import sip
# sip.setapi('QVariant', 2)

from PySide.QtCore import *
from PySide.QtGui import *
# from PIL import Image, ImageDraw

import datahandler
import commonfunctions
# import StringIO

class CreateCaseSettingsTab(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.parent = parent
        self.uidlabel = QLabel("Case Unique Identifier (UID): ")
        self.uidtext = QLineEdit()
        self.ucfnlabel = QLabel("Universal Case File Number (UCFN): ")
        self.ucfntext = QLineEdit()
        self.uidedit = QPushButton("Update")
        self.ucfnedit = QPushButton("Update")
        self.headercheck = QCheckBox("Add Header Statement")
        self.headerltext = QLineEdit()
        self.headerctext = QLineEdit()
        self.headerrtext = QLineEdit()
        self.footercheck = QCheckBox("Add Footer Statement")
        self.footerltext = QLineEdit()
        self.footerctext = QLineEdit()
        self.footerrtext = QLineEdit()
        self.mainbox = QVBoxLayout()
        self.uidbox = QHBoxLayout()
        self.ucfnbox = QHBoxLayout()
        self.headerbox = QHBoxLayout()
        self.footerbox = QHBoxLayout()
        self.ucfnbox.addWidget(self.ucfnlabel)
        self.ucfnbox.addWidget(self.ucfntext)
        self.ucfnbox.addWidget(self.ucfnedit)
        self.uidbox.addWidget(self.uidlabel)
        self.uidbox.addWidget(self.uidtext)
        self.uidbox.addWidget(self.uidedit)
        self.headerbox.addWidget(self.headercheck)
        self.headerbox.addWidget(self.headerltext)
        self.headerbox.addWidget(self.headerctext)
        self.headerbox.addWidget(self.headerrtext)
        self.footerbox.addWidget(self.footercheck)
        self.footerbox.addWidget(self.footerltext)
        self.footerbox.addWidget(self.footerctext)
        self.footerbox.addWidget(self.footerrtext)
        self.mainbox.addLayout(self.ucfnbox)
        self.mainbox.addLayout(self.uidbox)
        self.mainbox.addLayout(self.headerbox)
        self.mainbox.addLayout(self.footerbox)
        self.setLayout(self.mainbox)

        # connect actions
        self.ucfnedit.clicked.connect(self.updateSettings)
        self.uidedit.clicked.connect(self.updateSettings)

    def getSettings(self):
        self.currentucfn, self.currentuid = self.data.sql(self.data.getCaseSettings, [self.parent.currentcaseid], 1)
        self.ucfntext.setText(self.currentucfn)
        self.uidtext.setText(self.currentuid)

    def clearSettings(self):
        self.ucfntext.clear()
        self.uidtext.clear()

    def updateSettings(self):
        if self.sender() is self.ucfnedit:
            self.currentucfn = self.ucfntext.text()
        elif self.sender() is self.uidedit:
            self.currentuid = self.uidtext.text()
        self.data.sql(self.data.updateCaseSettings, [self.parent.currentcaseid, self.currentucfn, self.currentuid], 0)

        """
        self.addimageAction = QAction(QIcon(QDir.currentPath() + "/images/list-add.png"), "Add Image", self)
        self.delimageAction = QAction(QIcon(QDir.currentPath() + "/images/list-remove.png"), "Remove Selected Image", self)
        self.resizeAction = QAction(QIcon(QDir.currentPath() + "/images/transform-scale.png"), "Resize Selected Image", self)
        self.cropAction = QAction(QIcon(QDir.currentPath() + "/images/transform-crop-and-resize.png"), "Crop Selected Image", self)
        self.rotateAction = QAction(QIcon(QDir.currentPath() + "/images/transform-rotate.png"), "Rotate Selected Image", self)
        self.propertyAction = QAction(QIcon(QDir.currentPath() + "/images/document-properties.png"), "Edit Image Caption", self)

        self.imagetb = QToolBar()
        self.imagetb.addAction(self.addimageAction)
        self.imagetb.addAction(self.delimageAction)
        self.imagetb.addSeparator()
        self.imagetb.addAction(self.resizeAction)
        self.imagetb.addAction(self.cropAction)
        self.imagetb.addAction(self.rotateAction)
        self.imagetb.addSeparator()
        self.imagetb.addAction(self.propertyAction)
        self.imagetb.setStyleSheet("QToolBar { border: 0px }")

        self.delimageAction.setEnabled(False)
        self.resizeAction.setEnabled(False)
        self.cropAction.setEnabled(False)
        self.rotateAction.setEnabled(False)
        self.propertyAction.setEnabled(False)
 
        self.imageList = QListWidget()
        self.imageViewer = QLabel()
        self.imageScroll = QScrollArea()
        self.imageScroll.setWidget(self.imageViewer)
        self.imageScroll.setAlignment(Qt.AlignCenter)
        self.imageList.setMaximumWidth(150)
        self.imageList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.imageList.setAlternatingRowColors(True)
        self.imageList.setFrameStyle(QFrame.Panel)
        self.imageScroll.setFrameStyle(QFrame.Panel)
        self.mainBox = QVBoxLayout()
        self.topBox = QHBoxLayout()
        self.botBox = QHBoxLayout()
        self.topBox.addWidget(self.imagetb)
        self.botBox.addWidget(self.imageList)
        self.botBox.addWidget(self.imageScroll)
        self.mainBox.addLayout(self.topBox)
        self.mainBox.addLayout(self.botBox)
        self.setLayout(self.mainBox)
        # connect actions
        self.addimageAction.triggered.connect(self.addImage)
        self.delimageAction.triggered.connect(self.delImage)
        self.resizeAction.triggered.connect(self.resizeImage)
        self.cropAction.triggered.connect(self.cropImage)
        self.rotateAction.triggered.connect(self.rotateImage)
        self.propertyAction.triggered.connect(self.editCaption)
        self.imageList.itemSelectionChanged.connect(self.showImage)
        """
    """
    def addImage(self):
        filename = QFileDialog.getOpenFileName(self, "Open Image", QDir.homePath(), "Image files (*.png *.jpg *.bmp *.gif)")
        tmpcaption = filename[0].split("/")[-1]
        if tmpcaption != "":
            self.data.sql(self.data.insertImage, [filename[0], tmpcaption, self.parent.currentcaseid], 0)
            self.updateImageList()

    def delImage(self):
        self.checkMessage = QMessageBox.warning(self, "Delete Image", "Are you sure you want to delete the image?\n This action cannot be undone.", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if self.checkMessage is QMessageBox.StandardButton.Yes:
            self.data.sql(self.data.deleteImage, [self.parent.currentimageid], 0)
            self.updateImageList()
            print "dete it here"

    def editCaption(self):
        tmpimagecaption, ok = QInputDialog.getText(self, "Image Caption", "Modify the Image Caption:")
        if ok and tmpimagecaption:
            self.data.sql(self.data.updateImageCaption, [self.parent.currentimageid, tmpimagecaption], 0)
            self.updateImageList()

    def resizeImage(self):
        self.modresimg = None
        resdlg = ResizeDialog(self.parent.currentimageid, self)
        retval = resdlg.exec_()
        if retval == 1:
            self.outstring = StringIO.StringIO()
            self.modresimg.save(self.outstring, "PNG")
            self.data.sql(self.data.updateImageData, [self.outstring, self.parent.currentimageid], 0)
            self.outstring.close()
            self.updateImageList()

    def rotateImage(self):
        self.modrotimg = None
        rotdlg = RotateDialog(self.parent.currentimageid, self)
        retval = rotdlg.exec_()
        if retval == 1:
            self.outstring = StringIO.StringIO()
            self.modrotimg.save(self.outstring, "PNG")
            self.data.sql(self.data.updateImageData, [self.outstring, self.parent.currentimageid], 0)
            self.outstring.close()
            self.updateImageList()

    def cropImage(self):
        self.origimg = None
        self.crpval = None
        crpdlg = CropDialog(self.parent.currentimageid, self)
        retval = crpdlg.exec_()
        if retval == 1:
            self.outstring = StringIO.StringIO()
            self.croppedRegion = self.origimg.crop(self.crpval)
            self.croppedRegion.save(self.outstring, "PNG")
            self.data.sql(self.data.updateImageData, [self.outstring, self.parent.currentimageid], 0)
            self.outstring.close()
            self.updateImageList()
        print retval

    def updateImageList(self):
        self.imageList.clear()
        self.imageList.addItems(self.data.sql(self.data.updateImageList, [self.parent.currentcaseid], 1))
        for tmpaction in [self.delimageAction, self.resizeAction, self.cropAction, self.rotateAction, self.propertyAction]:
            if tmpaction.isEnabled() is True:
                tmpaction.setEnabled(False)
        self.imageViewer.clear()

    def showImage(self):
        for tmpaction in [self.delimageAction, self.resizeAction, self.cropAction, self.rotateAction, self.propertyAction]:
            if tmpaction.isEnabled() is False:
                tmpaction.setEnabled(True)
        self.currentimagedata, self.parent.currentimageid = self.data.sql(self.data.getImageValuesFromImageList, [self.imageList.currentItem().text(), self.parent.currentcaseid], 1)
        self.imageViewer.setPixmap(self.common.makePixmapFromString(self.currentimagedata))
        self.imageViewer.adjustSize()
    """
"""
class CropDialog(QDialog):
    def __init__(self, imageid, parent):
        QDialog.__init__(self, parent)
        self.parent = parent
        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.imgdata = self.data.sql(self.data.getImageDataFromImageId, [imageid], 1)
        self.origImg = Image.open(StringIO.StringIO(self.imgdata))
        self.imgPreview = QLabel()
        self.imgScroll = QScrollArea()
        self.imgScroll.setAlignment(Qt.AlignCenter)
        self.imgScroll.setWidget(self.imgPreview)
        self.mainBox = QVBoxLayout()
        self.topBox = QHBoxLayout()
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.leftSpin = QSpinBox()
        self.topSpin = QSpinBox()
        self.rightSpin = QSpinBox()
        self.botSpin = QSpinBox()
        self.leftSpin.setRange(0, self.origImg.size[0])
        self.topSpin.setRange(0, self.origImg.size[1])
        self.rightSpin.setRange(0, self.origImg.size[0])
        self.botSpin.setRange(0, self.origImg.size[1])
        for tmpSpin in [self.leftSpin, self.topSpin, self.rightSpin, self.botSpin]:
            tmpSpin.setSuffix(" px")
            self.topBox.addWidget(tmpSpin)
            tmpSpin.valueChanged.connect(self.cropImage)
        self.mainBox.addLayout(self.topBox)
        self.mainBox.addWidget(self.imgScroll)
        self.mainBox.addWidget(self.buttonBox)
        self.setLayout(self.mainBox)
        self.setWindowTitle("Crop Image")
        # connect actions
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.drawPreview(self.leftSpin.value(), self.topSpin.value(), self.rightSpin.value(), self.botSpin.value())

    def drawPreview(self, lval, tval, rval, bval):
        self.imgPreview.clear()
        self.previmg = self.origImg.copy()
        self.parent.origimg = self.origImg.copy()
        self.parent.crpval = (lval, tval, self.previmg.size[0] - rval, self.previmg.size[1] - bval)
        draw = ImageDraw.ImageDraw(self.previmg)
        draw.rectangle((lval, tval, self.previmg.size[0] - rval, self.previmg.size[1] - bval), outline=(255, 0, 0))
        self.previmg = self.previmg.convert("RGBA")
        self.imgPreview.setPixmap(self.common.makePixmapFromPIL(self.previmg))
        self.imgPreview.adjustSize()

    def cropImage(self):
        self.drawPreview(self.leftSpin.value(), self.topSpin.value(), self.rightSpin.value(), self.botSpin.value())
   
class RotateDialog(QDialog):
    def __init__(self, imageid, parent):
        QDialog.__init__(self, parent)
        self.parent = parent
        self.data = datahandler.DataHandler()
        self.imgdata = self.data.sql(self.data.getImageDataFromImageId, [imageid], 1)
        self.common = commonfunctions.CommonFunctions()
        self.imgPreview = QLabel()
        self.imgScroll = QScrollArea()
        self.imgScroll.setAlignment(Qt.AlignCenter)
        self.mainBox = QVBoxLayout()
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.rotateSpinner = QSpinBox()
        self.rotateSpinner.setRange(0, 360)
        self.rotateSpinner.setWrapping(True)
        self.rotateSpinner.setSuffix(" degrees")
        self.imgScroll.setWidget(self.imgPreview)
        self.mainBox.addWidget(self.rotateSpinner)
        self.mainBox.addWidget(self.imgScroll)
        self.mainBox.addWidget(self.buttonBox)
        self.setLayout(self.mainBox)
        self.setWindowTitle("Rotate Image Counter-Clockwise")
        # connect actions
        self.rotateSpinner.valueChanged.connect(self.rotateImage)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.originalimage = Image.open(StringIO.StringIO(self.imgdata))
        self.drawPreview(0)

    def accept(self):
        self.parent.modrotimg = self.rotatedimage
        QDialog.accept(self)

    def rotateImage(self):
        self.drawPreview(self.rotateSpinner.value())

    def drawPreview(self, angle):
        self.previewimage = self.originalimage
        self.rotatedimage = self.previewimage.rotate(angle, Image.NEAREST, 1)
        self.rotatedimage = self.rotatedimage.convert("RGBA")
        self.imgPreview.setPixmap(self.common.makePixmapFromPIL(self.rotatedimage))
        self.imgPreview.adjustSize()

class ResizeDialog(QDialog):
    def __init__(self, imageid, parent):
        QDialog.__init__(self, parent)
        self.parent = parent
        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.imgdata = self.data.sql(self.data.getImageDataFromImageId, [imageid], 1)
        self.wlabel = QLabel("Width: ")
        self.hlabel = QLabel("Height: ")
        self.wpxspin = QSpinBox()
        self.hpxspin = QSpinBox()
        self.imgpreview = QLabel()
        self.imgscroll = QScrollArea()
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.topbox = QHBoxLayout()
        self.botbox = QHBoxLayout()
        self.mainbox = QVBoxLayout()
        self.imgscroll.setWidget(self.imgpreview)
        self.imgscroll.setAlignment(Qt.AlignCenter)
        self.wpxspin.setSuffix(" px")
        self.hpxspin.setSuffix(" px")
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.origimg = Image.open(StringIO.StringIO(self.imgdata))
        self.topbox.addWidget(self.wlabel)
        self.topbox.addWidget(self.wpxspin)
        self.botbox.addWidget(self.hlabel)
        self.botbox.addWidget(self.hpxspin)
        self.mainbox.addLayout(self.topbox)
        self.mainbox.addLayout(self.botbox)
        self.mainbox.addWidget(self.imgscroll)
        self.mainbox.addWidget(self.buttons)
        self.setLayout(self.mainbox)
        self.setWindowTitle("Resize Image")
        self.wpxspin.setRange(1, self.origimg.size[0])
        self.hpxspin.setRange(1, self.origimg.size[1])
        self.wpxspin.setValue(self.origimg.size[0])
        self.hpxspin.setValue(self.origimg.size[1])
        self.wpxspin.valueChanged.connect(self.imgResize)
        self.hpxspin.valueChanged.connect(self.imgResize)
        self.drawPreview(self.origimg.size[0], self.origimg.size[1])

    def accept(self):
        self.parent.modresimg = self.resimg
        QDialog.accept(self)

    def imgResize(self):
        self.drawPreview(self.wpxspin.value(), self.hpxspin.value())
    
    def drawPreview(self, nwidth, nheight):
        self.previmg = self.origimg.copy()
        self.resimg = self.previmg.resize((nwidth, nheight), Image.ANTIALIAS)
        self.resimg = self.resimg.convert("RGBA")
        self.imgpreview.setPixmap(self.common.makePixmapFromPIL(self.resimg))
        self.imgpreview.adjustSize()
"""
